var baseUrl = "https://www.xaqtj.com/api/v1/";

var vm = new Vue({
    el: "#app",
    data: {
        title:"Hello Vue",
        totalMoneny:0,
        productList: [],
        curProduct:[],
        checkAllFlag: false,
        delFlag:false
    },
    filters:{
       formatMoney:function (value) {
           return "￥ " + value.toFixed(2);
       }
    },
    //初始化方法
    mounted:function () {

        this.cartView();
    },
    methods:{
        cartView: function(){
            var _this = this;
            axios.get(baseUrl + "json/cart")
            .then(function (response) {
                console.log(response.data);
              _this.productList = response.data.result.productList;
              _this.totalMoneny = response.data.result.totalMoney;
            })
            .catch(function (error) {
              console.log(error);
            });
        },
        changeMoney:function(product,way){
            if(way > 0){
                product.productQuentity++;
            }else{
                product.productQuentity--;
                if(product.productQuentity < 1){
                    product.productQuentity = 1; 
                }
            }
            this.calcTotalPrice();
        },
        selectedProduct:function(item){
            console.log(item);
            if(typeof item.checked == 'undefined') {
                Vue.set(item,"checked",true); //vue全局注册
               // this.$set(item,"checked",true); //vue局部注册
            }else{
                item.checked = !item.checked;
            }
            this.calcTotalPrice();
        },
        //全选和取消全选
        checkAll:function(flag) {
            this.checkAllFlag = flag;
            var _this = this;
            this.productList.forEach(function(item,index){
                if(typeof item.checked == 'undefined') {
                    Vue.set(item,"checked",_this.checkAllFlag);
                }else{
                    item.checked = _this.checkAllFlag;
                }

            });
            this.calcTotalPrice();
        },
        //计算商品总价格
        calcTotalPrice:function(){
            var _this = this;
            this.totalMoneny = 0;
            this.productList.forEach(function(item,index){
                if(item.checked == true){
                    _this.totalMoneny += item.productPrice * item.productQuentity;
                }
            });
        },
        delConfirm: function(item){
            this.delFlag = true;
            this.curProduct = item;
        },
        delProduct: function(){
            var index = this.productList.indexOf(this.curProduct);
            this.productList.splice(index,1);
            this.delFlag = false;
        }
    }
});

//全局过滤器
Vue.filter("money",function(value,type){
    return "￥ " + value.toFixed(2) + type;
})